package com.shoppingmall.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.Hashtable;

/**
 * Created by ZHY on 2017/7/28.
 * 生成二维码
 */
public class CodeTools {
    public static Bitmap create2Dcode(String text) {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 0);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//提高容错率
        BitMatrix matrix = null;
        try {
            matrix = new MultiFormatWriter().encode(text,
                    BarcodeFormat.QR_CODE, 220, 220, hints);

        } catch (WriterException e) {
            e.printStackTrace();
        }
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        // 二维矩阵转为一维像素数组
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = 0xff000000;
                } else {
                    pixels[y * width + x] = 0xffffffff;
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        // 通过像素数组生成图片
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    /**
     * 生成二维码图片（自定义宽高）
     *
     * @param text 内容
     * @param w    宽度
     * @param h    高度
     * @return Bitmap
     */
    public static Bitmap create2DcodeWithwh(String text, int w, int h) {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 0);
        BitMatrix matrix = null;
        try {
            matrix = new MultiFormatWriter().encode(text,
                    BarcodeFormat.QR_CODE, w, h, hints);

        } catch (WriterException e) {
            e.printStackTrace();
        }
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        // 二维矩阵转为一维像素数组
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = 0xff000000;
                } else {
                    pixels[y * width + x] = 0xffffffff;
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        // 通过像素数组生成图片
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    /**
     * 生成带图片的二维码（需要第一步先生成二维码bitmap）
     *
     * @param context 上下文对象
     * @param qr      已经生成的二维码
     * @param rid     二维码中图片的id
     * @param width   二维码中图片的宽度
     */
    public static void createQRcodeBitmapwithPicture(Context context,
                                                     Bitmap qr, int rid, int width) {
        Bitmap picture = BitmapFactory.decodeResource(context.getResources(),
                rid);
        // 头像图片大小
        int strokeWidth = 5;// 边框宽度
        int picture_W = picture.getWidth();
        int picture_H = picture.getHeight();
        if (picture_W > width) {
            double param = ((double) picture_W) / ((double) (width));
            picture_H = ((int) (((double) picture_H) / param));
            picture_W = width;
            picture = Bitmap.createScaledBitmap(picture, picture_W, picture_H,
                    true);
        }
        // 设置头像图片显示的位置
        int left = (qr.getWidth() - picture_W) / 2;
        int top = (qr.getHeight() - picture_H) / 2;
        int right = left + picture_W;
        int bottom = top + picture_H;
        Rect rect = new Rect(left, top, right, bottom);

        // 取得二维码图片上的画笔，也就是在二维码上绘制我们的头像
        Canvas canvas = new Canvas(qr);
        // 设置我们要和绘制的范围大小，也就是头像的范围大小
        Rect rect2 = new Rect(0, 0, picture_W, picture_H);
        // 画笔对象
        Paint paint = new Paint();
        // 设置画笔颜色
//        paint.setColor(context.getResources().getColor(R.color.bg_color));
        // 设置画笔宽度
//        paint.setStrokeWidth(strokeWidth);
        Rect side = new Rect(left, top, right, bottom);
        // 开始绘制
        canvas.drawBitmap(picture, rect2, rect, paint);
    }

    /**
     * 生成logo的二维码（第二种方法，一步生成，上面的两步可以分开使用）
     *
     * @param string 二维码中包含的文本信息
     * @param mBitmap logo图片
     * @param format  编码格式
     * @return Bitmap 位图
     * @throws WriterException
     */
    private static final int IMAGE_HALFWIDTH = 50;//宽度值，影响中间图片大小

    public static Bitmap createCode(Context context, String string, int rid) {
        Bitmap mBitmap = BitmapFactory.decodeResource(context.getResources(),
                rid);
        Matrix m = new Matrix();
        float sx = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getWidth();
        float sy = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getHeight();
        m.setScale(sx, sy);//设置缩放信息
        //将logo图片按martix设置的信息缩放
        mBitmap = Bitmap.createBitmap(mBitmap, 0, 0,
                mBitmap.getWidth(), mBitmap.getHeight(), m, false);
        MultiFormatWriter writer = new MultiFormatWriter();
        Hashtable<EncodeHintType, String> hst = new Hashtable<EncodeHintType, String>();
        hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");//设置字符编码
        BitMatrix matrix = null;//生成二维码矩阵信息
        try {
            matrix = writer.encode(string, BarcodeFormat.QR_CODE, 500, 500, hst);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        int width = matrix.getWidth();//矩阵高度
        int height = matrix.getHeight();//矩阵宽度
        int halfW = width / 2;
        int halfH = height / 2;
        int[] pixels = new int[width * height];//定义数组长度为矩阵高度*矩阵宽度，用于记录矩阵中像素信息
        for (int y = 0; y < height; y++) {//从行开始迭代矩阵
            for (int x = 0; x < width; x++) {//迭代列
                if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH
                        && y > halfH - IMAGE_HALFWIDTH
                        && y < halfH + IMAGE_HALFWIDTH) {//该位置用于存放图片信息
                    //记录图片每个像素信息
                    pixels[y * width + x] = mBitmap.getPixel(x - halfW
                            + IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
                } else {
                    if (matrix.get(x, y)) {//如果有黑块点，记录信息
                        pixels[y * width + x] = 0xff000000;//记录黑块信息
                    }
                }

            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        // 通过像素数组生成bitmap
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }
}
